package processes

import (
	"encoding/json"
	"fmt"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/constants"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/message"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/netWork"
)

type SmsProcess struct {
}

func (sp *SmsProcess) ForwardGroupMsg(data string) {
	var smsMsg message.SmsMsg
	err := json.Unmarshal([]byte(data), &smsMsg)
	for userId, up := range userManagerProcess.GetAllOnlineUser() {
		if userId == smsMsg.Sender.UserId || smsMsg.Receiver.UserId != 0 && smsMsg.Receiver.UserId != userId {
			continue
		}
		smsMsg.Receiver = message.User{
			UserId:   up.userId,
			UserName: up.userName,
		}
		err = sp.forwardMsgToUser(smsMsg, up.Conn)
		if err != nil {
			fmt.Printf("SendGroupMsg send msg to user:%s(%d) fail ,err = %v\n", up.userName, userId, err)
		}
	}
	return
}

func (sp *SmsProcess) forwardMsgToUser(smsMsg message.SmsMsg, conn netWork.Conn) (err error) {
	// 设置message结构体
	msg := message.Message{}

	// 设置类型
	msg.SetType(constants.MSG_TYPE_SMS_MSG_FORWARD)

	// 过滤掉非法的消息
	smsMsg.Content = sp.filterIllegalContent(smsMsg.Content)

	// 添加转发的数据
	err = msg.SetData(smsMsg)
	if err != nil {
		fmt.Println("SendMsgToUser SetData fail:", err)
		return
	}
	conn.SetMsg(msg)
	conn.Send()
	return
}

func (sp *SmsProcess) filterIllegalContent(smsContent string) string {
	return smsContent
}
